package com.his.admin.service;

import com.his.util.constant.RedisConstant;
import com.his.util.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{authorization}")
@Component
@Slf4j
public class WebSocketService {
    private Session session;
    private static ConcurrentHashMap<Integer, WebSocketService> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("authorization") Integer authorization) {
        log.info("----------------------------------------------------------------------------");
        this.session = session;
        webSocketMap.put(authorization, this);
    }

    @OnClose
    public void onClose() {
        log.info("----------------------------------------------------------------------------");
        webSocketMap.forEach((k, v) -> {
            if (v.equals(this)) {
                webSocketMap.remove(k);
            }
        });
    }

    @OnMessage
    public void onMessage(String message, Session session) {
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendRegistration(Integer userId, String value) {
        try {
            webSocketMap.get(userId).session.getBasicRemote().sendText(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}